package com.zxj.camerademo;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.VideoView;

import com.zxj.camerademo.utils.DecodeImgTask;
import com.zxj.camerademo.utils.FileUtil;

import java.io.File;

public class CaptureActivity extends AppCompatActivity implements View.OnClickListener {

    private  String AUTHORITY = "com.zxj.camerademo.fileProvider";//FileProvider的签名(后面会介绍)
    private final static int REQUEST_CODE_CAPTURE_SMALL = 0x8001;
    private final static int REQUEST_CODE_CAPTURE_RAW = 0x8002;//startActivityForResult时的请求码
    private final static int REQUEST_CODE_CAPTURE = 0x8003;
    private final static int REQUEST_CODE_CAPTURE_CROP = 0x8004;
    private final static int REQUEST_CODE_ALBUM = 0x8005;
    private final static int REQUEST_CODE_VIDEO = 0x8006;
    private ImageView ivResult;
    private VideoView videoView;
    private File imageFile;//拍照后保存的照片
    private File imageCropFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_capture);

        Button btnCaptureSmall = findViewById(R.id.btnCaptureSmall);
        Button btnCaptureRaw = findViewById(R.id.btnCaptureRaw);
        Button btnCaptureAndClip = findViewById(R.id.btnCaptureAndClip);
        Button btnAlbumAndClip = findViewById(R.id.btnAlbumAndClip);
        Button btnCaptureVideo = findViewById(R.id.btnCaptureVideo);
        ivResult = findViewById(R.id.ivResult);
        videoView = findViewById(R.id.videoView);

        btnCaptureSmall.setOnClickListener(this);
        btnCaptureRaw.setOnClickListener(this);
        btnCaptureAndClip.setOnClickListener(this);
        btnAlbumAndClip.setOnClickListener(this);
        btnCaptureVideo.setOnClickListener(this);
    }

    //拍照(返回缩略图)
    private void gotoCaptureSmall(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        PackageManager pm = getPackageManager();
        intent.resolveActivity(pm);
        startActivityForResult(intent,REQUEST_CODE_CAPTURE_SMALL);
    }

    //拍照(返回原始图)
    private void gotoCaptureRaw(){
        imageFile = FileUtil.createImageFile(false);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri imgUri = FileProvider.getUriForFile(this,AUTHORITY, imageFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
        }else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
        }
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        startActivityForResult(intent,REQUEST_CODE_CAPTURE_RAW);
    }

    // 拍照 + 裁切
    private void gotoCaptureCrop() {
        imageFile = FileUtil.createImageFile(false);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri imgUri = FileProvider.getUriForFile(this,AUTHORITY, imageFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
        }else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
        }
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent,REQUEST_CODE_CAPTURE);
    }

    //打开系统相册
    private void gotoGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_CODE_ALBUM);
    }

    //录制视频
    private void gotoCaptureVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_CODE_VIDEO);
        }
    }

    private void gotoCrop(Uri sourceUri) {
        imageCropFile = FileUtil.createImageFile(true);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);    //X方向上的比例
        intent.putExtra("aspectY", 1);   //Y方向上的比例
        intent.putExtra("outputX", 500);  //裁剪区的宽
        intent.putExtra("outputY", 500); //裁剪区的高
        intent.putExtra("scale ", true);  //是否保留比例
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.setDataAndType(sourceUri, "image/*");  //设置数据源

            Uri imgCropUri = Uri.fromFile(imageCropFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imgCropUri); //设置输出  不需要ContentUri,否则失败
            Log.d("tag", "输入"+sourceUri);
            Log.d("tag", "输出 "+Uri.fromFile(imageCropFile));
        } else {
            intent.setDataAndType(Uri.fromFile(imageFile), "image/*");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageCropFile));
        }
        startActivityForResult(intent, REQUEST_CODE_CAPTURE_CROP);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Activity.RESULT_OK) {
            switch (requestCode){
                case REQUEST_CODE_CAPTURE_SMALL:
                    if(null != data){
                        Bundle bundle = data.getExtras();
                        Bitmap imageBitmap = (Bitmap) bundle.get("data");
                        ivResult.setImageBitmap(imageBitmap);
                    }
                    break;
                case REQUEST_CODE_CAPTURE_RAW:
                    //拍照成功后，压缩图片，显示结果
                    new DecodeImgTask(ivResult).execute(imageFile.getAbsolutePath());
                    break;
                case REQUEST_CODE_CAPTURE:
                    //拍照成功后，裁剪
                    Uri sourceUri = FileProvider.getUriForFile(this, AUTHORITY, imageFile);//通过FileProvider创建一个content类型的Uri
                    gotoCrop(sourceUri);
                    break;
                case REQUEST_CODE_CAPTURE_CROP:
                    //裁剪成功后，显示结果
                    ivResult.setImageBitmap(BitmapFactory.decodeFile(imageCropFile.getAbsolutePath()));
                    break;
                case REQUEST_CODE_ALBUM:
                    //从相册选择照片后，裁剪
                    if(data != null) {
                        Uri uri = data.getData();
                        gotoCrop(uri);
                    }
                    break;
                case REQUEST_CODE_VIDEO:
                    //录制视频成功后播放
                    if(data != null) {
                        Uri uri = data.getData();
                        videoView.setVisibility(View.VISIBLE);
                        videoView.setVideoURI(uri);
                        videoView.start();
                        Log.d("tag", "视频uri="+uri);
                    }
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnCaptureSmall:
                //拍照(返回缩略图)
                gotoCaptureSmall();
                break;
            case R.id.btnCaptureRaw:
                gotoCaptureRaw();
                //拍照
                break;
            case R.id.btnCaptureAndClip:
                //拍照 + 裁切
                gotoCaptureCrop();
                break;
            case R.id.btnAlbumAndClip:
                //相册 + 裁切
                gotoGallery();
                break;
            case R.id.btnCaptureVideo:
                //录视频 + 播放
                gotoCaptureVideo();
                break;
        }
    }
}
